<script setup lang="ts">
import { reactive, ref, onBeforeMount,onMounted} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { user as useUser } from '@/store'
import { ElMessage as message } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { verifyPic as _verifyPic } from '@/assets/imgs/verifyPic'
import mockRequest from '@/mock/request'

const router = useRouter()
const route = useRoute()
const userStore = useUser()
const formState: { phone: string; verifyCode: string } = reactive({
	phone: '',
	verifyCode: '',
})

const isLoading = ref(false)
const formRef = ref<FormInstance>()
const time = ref(0)
let timer: any
let inputList:NodeListOf<HTMLElement>
const phoneReg=/^\d{11}$/

const rules = reactive<FormRules>({
	phone: [
		{ required: true, message: '请输入你的手机号!', trigger: 'blur' },
		{ pattern:phoneReg, message: '请输入正确格式的手机号!', trigger: 'blur' },
	],
	verifyCode: [
		{ required: true, message: '请输入你的验证码!', trigger: 'blur' },
		{ pattern: /^\d{6}$/, message: '请输入6位数字的验证码!', trigger: 'blur' },
	],
})

onBeforeMount(() => {
	const { phone } = userStore.loginInfo
	if (phone) {
		formState.phone = phone
	}
})

onMounted(()=>{
	inputList=document.querySelectorAll('.phone-form .el-input__inner')
})

const resetForm=(formEl: FormInstance | undefined)=>{
	if (!formEl) return
	formEl.resetFields()
}

const bindSendVerifyCode = async () => {
  if(!formState.phone){
    message.warning('请填写手机号！')
    return
  }
  if(!phoneReg.test(formState.phone)){
    message.warning('请填写正确格式的手机号！')
    return
  }
	const res = await mockRequest(() => ({ code: 200, expire: 10 }), true, '获取验证码中...')
	console.log(res)
	if (res && res.code) {
		time.value = res.expire
		timer = setInterval(() => {
			if (time.value <= 0) {
				clearInterval(timer)
				timer = 0
				return
			}
			time.value--
		}, 1000)
	} else {
		message.warning('获取验证码失败！')
	}
}

const  handleInputsKeyDown=(e: KeyboardEvent)=>{
  if(e.key=='ArrowUp' || e.key=='ArrowDown') e.preventDefault()
}

const handleInputsKeyUp=(index:number,e: KeyboardEvent)=>{
	if (e.key == 'Enter') submitForm(formRef.value)
	const toggleFocus=(direction:'down' | 'up')=>{
		let i:number
		if(direction=='up'){
			i=index-1
		  if(i<0) i=inputList.length-1
		}
		else{
			i=index+1
		  if(i>inputList.length-1) i=0
		}
		inputList[i].focus()	
  }
	if(e.key=='ArrowUp'){
		toggleFocus('up')
	}
	if(e.key=='ArrowDown'){
		toggleFocus('down')
	}
}

const submitForm = async (formEl: FormInstance | undefined) => {
	if (isLoading.value) return
	try {
		await formEl?.validate()
		isLoading.value = true
		const { phone, verifyCode } = formState
		const res = await userStore.loginByPhone({ phone, verifyCode })
		isLoading.value = false

		if (res && res.code == 200) {
			const { id } = userStore.loginInfo
			if (route.query.redirect && res.id === id)
				// 防止重定向到没有权限的页面
				router.push(decodeURIComponent(route.query.redirect as string))
			else router.push('/')
			userStore.$patch((s) => {
				s.loginInfo = { ...s.loginInfo, id: res.id, phone: formState.phone, activeTab: 'phone' }
			})
		}
		if (res && res.code == 201) message.warning('手机号错误！')
	} catch (error) {
		console.log(error)
	}
}
</script>

<template>
	<el-form class="phone-form" ref="formRef" :model="formState" :rules="rules">
		<el-form-item prop="phone">
			<el-input v-model="formState.phone" placeholder="请输入手机号" prefix-icon="Iphone" clearable @keyup="handleInputsKeyUp(0,$event)" @keydown="handleInputsKeyDown"></el-input>
		</el-form-item>

		<el-form-item prop="verifyCode">
			<el-input v-model="formState.verifyCode" placeholder="请输入验证码" prefix-icon="Key" style="width: 60%; margin-right: 10px" clearable @keyup="handleInputsKeyUp(1,$event)" @keydown="handleInputsKeyDown"> </el-input>
			<el-button :disabled="!!time" @click="bindSendVerifyCode">获取验证码{{ `${time ? `(${time})` : ''}` }}</el-button>
		</el-form-item>

		<el-form-item>
			<el-button type="primary" @click="submitForm(formRef)" class="phone-form-button" style="margin-top: 10px" :loading="isLoading"> 登录 </el-button>
		</el-form-item>
	</el-form>
</template>

<style lang="scss" scoped>
.phone-form {
	.phone-form-button {
		width: 100%;
	}
}
</style>
